<?php
/***
 * Candy框架 扩展类库
 * 
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2019-08-01 21:01:16 $   
 */

declare (strict_types = 1);
namespace Candy\Core;

defined('CANDY') OR die('You Are A Bad Guy. o_O???');

final Class Addon {
	
	/**
	 * 检查Addon
	 *
	 * @param	$addonName	Addon名称
	 */
	public static function checkAddon(string $addonName): bool
	{
		if(is_null(G('Addons'))) return false;
		$path = ADDONPATH;
		if(!is_dir($path)) return false;
		isset($setting) OR $setting = loadConfig('Addon');
		$addon_list = $setting['ADDON_LIST'];
		$conffile = ADDONPATH . $addonName .'/conf.php';
		if(fileExistsCase($conffile)){
			$conf = (array)include($conffile);
			!isset($conf['enable']) && $conf['enable'] = isset($addon_list[$addonName]['enable']) ? $addon_list[$addonName]['enable'] : 0;
			if($conf['enable']){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	/**
	 * 获取使用的Addon
	 *
	 * @param	$force	强制关闭验证
	 */
	public static function getEnableAddons(int $force = 0): array
	{
		if(is_null(G('Addons'))) return [];
		$addons = self::getAddons($force);
		static $enable_addons = [];
		if(!empty($enable_addons) && !$force) return $enable_addons;
		
		foreach($addons as $k=>$addon){
			if(!empty($addon['installed']) && !empty($addon['enable'])){
				$enable_addons[$k] = $addon;
			}
		}
		return $enable_addons;
	}
	
	/**
	 * 获取Addon
	 *
	 * @param	$force	强制关闭验证
	 */
	public static function getAddons(int $force = 0): array
	{
		if(is_null(G('Addons'))) return [];
		static $addons = [];
		$path = ADDONPATH;
		if(!is_dir($path)) return [];
		$addon_path = INCPATH.'Addon.inc.php';
		$setting = is_file($addon_path) ? include($addon_path) : ['ADDON_LIST'=>[]];
		$addon_list = $setting['ADDON_LIST'];
		if($force){
			$arr = dirs($path);
		}else{
			$arr = array_keys($addon_list);
		}
		foreach($arr as $v){
			$conffile = $path.$v.'/conf.php';
			$conf = is_file($conffile) ? (array)include($conffile) : [];
			!isset($conf['enable']) && $conf['enable'] = isset($addon_list[$v]['enable']) ? $addon_list[$v]['enable'] : 0;
			!isset($conf['installed']) && $conf['installed'] = isset($addon_list[$v]['installed']) ? $addon_list[$v]['installed'] : 0;
			!isset($conf['addonid']) && $conf['addonid'] = isset($addon_list[$v]['addonid']) ? $addon_list[$v]['addonid'] : 0;
			!isset($conf['rank']) && $conf['rank'] = isset($addon_list[$v]['rank']) ? $addon_list[$v]['rank'] : 100; // 按照正序排序
			$addons[$v] = $conf;
		}
		$addons = \Candy\Extend\Arr::arraySort($addons, 'rank');
		return $addons;
	}
	
	/**
	 * 检查Addon
	 *
	 * @param	$addonName	Addon名称
	 */
	public static function getAddonAuth(string $addonName): bool
	{
		if(is_null(G('Addons'))) return false;
		$conffile = ADDONPATH . $addonName .'/conf.php';
		if(fileExistsCase($conffile)){
			$conf = (array)include($conffile);
			if(isset($conf['auth']) && $conf['auth'] == 1){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
}
